//
//  WebController.m
//  MINFOBBS
//
//  Created by juvid on 13-11-21.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "WebController.h"
#import "DetectionSystemVersion.h"
#import "MainSearchViewController.h"
@interface WebController (){
    NSArray *arrMessageContent;
    NSString *strNumber;

}

@end

@implementation WebController
@synthesize strPhone;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self BackButton];
// [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:106591145288Ccontent:CZ601988"]];
    [self.webView setScalesPageToFit:YES];
    [self.webView setSuppressesIncrementalRendering:YES];
//    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"tel:02164470993%7Cname:%E4%B9%90%E6%B1%9F%E5%B0%8F%E5%90%83%E4%B8%96%E7%95%8C"]];
    [self.webView loadRequest:self.requestUrl];
    // Do any additional setup after loading the view from its nib.
}
- (void)viewWillDisappear:(BOOL)animated{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}
-(void)BackButton{
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
     NSLog(@"%f",webView.scrollView.contentSize.height);

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *strUrl=[ NSString stringWithFormat:@"%@",request.URL];
    strUrl=[strUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSRange rang;
    if ([strUrl hasPrefix:@"tel:"]||[strUrl hasPrefix:@"sms:"]||[strUrl hasPrefix:@"reopen:"]) {
        if ([strUrl hasPrefix:@"tel:"]) {
            rang=[strUrl rangeOfString:@"|Cname"];
            strUrl=[strUrl substringToIndex:rang.location];
            UIAlertView *alrTell=[[UIAlertView alloc]initWithTitle:@"呼叫" message:strUrl delegate:self cancelButtonTitle:@"呼叫" otherButtonTitles:@"取消", nil];
            [alrTell show];
          
        }
        else if ([strUrl hasPrefix:@"sms:"])
        {
            [self GetMessage:[strUrl componentsSeparatedByString:@"|"]];
        }
        else if([strUrl hasPrefix:@"reopen:"]){
             rang=[strUrl rangeOfString:@"reopen:"];
            strUrl=[strUrl substringFromIndex:rang.length+rang.location];
            UINavigationController *navControl=[self.navigationController.parentViewController.childViewControllers objectAtIndex:1];
            MainSearchViewController *mainSearch=(MainSearchViewController *)[navControl .childViewControllers objectAtIndex:1];
           strUrl=[strUrl  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            mainSearch.strSearch=strUrl;
            mainSearch.isUrl=5;
            [self.navigationController popViewControllerAnimated:YES];
            [mainSearch WebUrl];


//            [navControl popToViewController:mainSearch animated:YES];
            }
        return NO;
    }
    
//    NSLog(@"地址 %@",request.URL);
     return YES;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString *str=[alertView buttonTitleAtIndex:buttonIndex];
    if ([str isEqual:@"呼叫"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:alertView.message]];
    }
    else if([str isEqual:@"查询"]){
        [self sendSMS:strNumber recipientList:arrMessageContent];
        strNumber=Nil;
        arrMessageContent=Nil;
    }

}
//解析短信内容
-(void)GetMessage:(NSArray *)arr{
    
    NSRange rang;
    NSString *strTitle;
    NSString *strMessage;
    //        [self sendSMS:@"CZ601988" recipientList:arr];
    for (int i=0; i<arr.count; i++) {
        NSString *str=[arr objectAtIndex:i];
        if ([str hasPrefix:@"sms:"]) {
            rang=[str rangeOfString:@"sms:"];
            str=[str substringFromIndex:rang.location+rang.length];
            arrMessageContent=[[NSArray alloc]initWithObjects:str, nil];
            
        }
        else if([str hasPrefix:@"content:"]){
            rang=[str rangeOfString:@"content:"];
            strNumber=[str substringFromIndex:rang.location+rang.length];
        }
        else if([str hasPrefix:@"alerttitle:"]){
            rang=[str rangeOfString:@"alerttitle:"];
            strTitle=[str substringFromIndex:rang.location+rang.length];
            
        }
        else if([str hasPrefix:@"alertcontent:"]){
            rang=[str rangeOfString:@"alertcontent:"];
            strMessage=[NSString stringWithFormat:@"%@\n\n（点播资费1元/条）详询118114转理财 （只支持电信手机）",[str substringFromIndex:rang.location+rang.length]];
            
        }
    }
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:strTitle message:strMessage delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"查询", nil];
    [alr show];
    strTitle=Nil;
    strMessage=Nil;
}

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText]){
            controller.body = bodyOfMessage;
            controller.recipients = recipients;
            controller.messageComposeDelegate = self;
            [self presentViewController:controller animated:YES completion:Nil];
    }
}
// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:Nil];
    [self ShowHUD];
    if (result==MessageComposeResultCancelled) {
        HUD.labelText=@"取消了发送";
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDProblem"]];
        HUD.mode = MBProgressHUDModeCustomView;
    }
    else if(result==MessageComposeResultSent){
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDTrue"]];
        HUD.mode = MBProgressHUDModeCustomView;
        HUD.labelText=@"发送成功";
        
    }
    else{
        HUD.labelText=@"发送失败";
        HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDFlase"]];
        HUD.mode = MBProgressHUDModeCustomView;
        
    }
    [HUD hide:YES afterDelay:1];
}
-(void)ShowHUD{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.delegate = self;
    HUD.labelText = @"";
    [self.view addSubview:HUD];
    [HUD show:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
